<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useItemsStore } from '../../stores/items'
import { useInventoryStore } from '../../stores/inventory'
import { ElMessage, ElMessageBox } from 'element-plus'
import IconSvg from '../../components/icons/IconSvg.vue'
import { messageHelper } from '../../utils/messageHelper'

const route = useRoute()
const router = useRouter()
const itemsStore = useItemsStore()
const inventoryStore = useInventoryStore()

const itemId = ref(route.params.id)
const item = ref(null)
const loading = ref(true)
const isEditing = ref(false)

// 计算属性，根据当前categoryId获取分类名称
const categoryName = computed(() => {
  return itemsStore.getCategoryName(editForm.value.categoryId)
})

// 编辑表单
const editForm = ref({
  name: '',
  categoryId: '',
  location: '',
  quantity: 0,
  purchaseDate: '',
  expiryDate: '',
  notes: '',
  icon: '',
  status: '正常使用'
})

// 获取物品详情
const fetchItemDetails = async () => {
  loading.value = true
  try {
    // 尝试从 itemsStore 获取物品详情
    const foundItem = await itemsStore.getItemById(itemId.value)
    if (foundItem) {
      item.value = { ...foundItem }
      // 填充编辑表单
      Object.keys(editForm.value).forEach(key => {
        if (item.value[key] !== undefined) {
          editForm.value[key] = item.value[key]
        }
      })

      // 确保编辑表单使用categoryId而不是category
      if (item.value.categoryId) {
        editForm.value.categoryId = item.value.categoryId
      }
    } else {
      // 尝试从模拟数据中获取
      if (itemsStore.dataSource === 'mock' && typeof itemsStore.initMockData === 'function') {
        // 确保模拟数据已加载
        if (itemsStore.items.length === 0) {
          itemsStore.initMockData()
        }
        
        // 从模拟数据中查找
        const mockItem = itemsStore.items.find(i => i.id.toString() === itemId.value.toString())
        if (mockItem) {
          item.value = { ...mockItem }
          // 填充编辑表单
          Object.keys(editForm.value).forEach(key => {
            if (item.value[key] !== undefined) {
              editForm.value[key] = item.value[key]
            }
          })
          
          // 确保编辑表单使用categoryId而不是category
          if (item.value.categoryId) {
            editForm.value.categoryId = item.value.categoryId
          }
          
          ElMessage.warning('无法连接到后端服务，显示本地数据')
          return
        }
      }
      
      ElMessage.error('找不到该物品')
      router.push('/dashboard/items')
    }
  } catch (error) {
    console.error('获取物品详情失败:', error)
    
    // 尝试从模拟数据中获取
    if (typeof itemsStore.initMockData === 'function') {
      // 确保模拟数据已加载
      if (itemsStore.items.length === 0) {
        itemsStore.initMockData()
      }
      
      // 从模拟数据中查找
      const mockItem = itemsStore.items.find(i => i.id.toString() === itemId.value.toString())
      if (mockItem) {
        item.value = { ...mockItem }
        // 填充编辑表单
        Object.keys(editForm.value).forEach(key => {
          if (item.value[key] !== undefined) {
            editForm.value[key] = item.value[key]
          }
        })
        
        // 确保编辑表单使用categoryId而不是category
        if (item.value.categoryId) {
          editForm.value.categoryId = item.value.categoryId
        }
        
        ElMessage.warning('无法连接到后端服务，显示本地数据')
      } else {
        ElMessage.error('找不到该物品')
        router.push('/dashboard/items')
      }
    } else {
    ElMessage.error('获取物品详情失败: ' + error.message)
      router.push('/dashboard/items')
    }
  } finally {
    loading.value = false
  }
}

// 启用编辑模式
const enableEditing = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  isEditing.value = false
  // 重置表单数据
  Object.keys(editForm.value).forEach(key => {
    if (item.value && item.value[key] !== undefined) {
      editForm.value[key] = item.value[key]
    }
  })
}

// 保存编辑
const saveChanges = async () => {
  try {
    // 创建要提交的数据对象
    const itemToSubmit = {...editForm.value};
    
    // 确保删除category字段，不传递给后端
    if ('category' in itemToSubmit) {
      delete itemToSubmit.category;
    }
    
    // 记录物品原始信息，用于比较变更内容
    const originalItem = { ...item.value };
    
    // 在实际应用中，应当发送请求到服务器保存更改
    await itemsStore.updateItem(itemId.value, itemToSubmit)
    
    // 确定变更的字段，构建变更详情
    const changedFields = [];
    if (originalItem.name !== itemToSubmit.name) changedFields.push(`名称从"${originalItem.name}"变更为"${itemToSubmit.name}"`);
    if (originalItem.categoryId !== itemToSubmit.categoryId) {
      const oldCategoryName = itemsStore.getCategoryName(originalItem.categoryId);
      const newCategoryName = itemsStore.getCategoryName(itemToSubmit.categoryId);
      changedFields.push(`分类从"${oldCategoryName}"变更为"${newCategoryName}"`);
    }
    if (originalItem.location !== itemToSubmit.location) changedFields.push(`位置从"${originalItem.location}"变更为"${itemToSubmit.location}"`);
    if (originalItem.quantity !== itemToSubmit.quantity) changedFields.push(`数量从${originalItem.quantity}变更为${itemToSubmit.quantity}`);
    if (originalItem.purchaseDate !== itemToSubmit.purchaseDate) changedFields.push(`购买日期变更`);
    if (originalItem.expiryDate !== itemToSubmit.expiryDate) changedFields.push(`过期日期变更`);
    if (originalItem.status !== itemToSubmit.status) changedFields.push(`状态从"${originalItem.status}"变更为"${itemToSubmit.status}"`);
    
    // 构建变更详情文本
    const changeDetails = changedFields.join('，');
    
    // 记录活动
    if (changedFields.length > 0) {
      await messageHelper.recordItemUpdated({ 
        ...itemToSubmit, 
        id: itemId.value 
      }, itemToSubmit.location, changeDetails);
    }
    
    // 如果数量减少到低于阈值，创建库存通知
    if (originalItem.quantity > itemToSubmit.quantity && itemToSubmit.quantity <= 3) {
      await messageHelper.createLowStockNotification({
        id: itemId.value,
        name: itemToSubmit.name,
        quantity: itemToSubmit.quantity,
        unit: '个', // 这里可以根据物品类型动态设置单位
        locationId: itemToSubmit.locationId
      });
    }
    
    // 重新获取最新数据以确保UI更新
    await fetchItemDetails()
    isEditing.value = false
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 删除物品
const deleteItem = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除物品 "${item.value.name}" 吗？`, '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 保存物品信息，用于记录活动
    const deletedItem = { ...item.value };
    const locationName = deletedItem.location;
    
    // 在实际应用中，应当发送请求到服务器删除物品
    await itemsStore.deleteItem(itemId.value)
    
    // 记录删除活动
    await messageHelper.recordItemDeleted({
      id: itemId.value,
      name: deletedItem.name,
      locationId: deletedItem.locationId
    }, locationName);
    
    ElMessage.success('物品已删除')
    router.push('/dashboard/items')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 增加物品数量
const increaseQuantity = async () => {
  if (!item.value) return
  try {
    const newQuantity = item.value.quantity + 1
    const originalQuantity = item.value.quantity;
    
    // 在实际应用中，应当发送请求到服务器更新数量
    await inventoryStore.updateItemQuantity(itemId.value, newQuantity)
    
    // 记录物品更新活动
    await messageHelper.recordItemUpdated({
      id: itemId.value,
      name: item.value.name,
      quantity: newQuantity,
      locationId: item.value.locationId
    }, item.value.location, `数量从${originalQuantity}增加到${newQuantity}`);
    
    // 重新获取最新数据以确保UI更新
    await fetchItemDetails()
    ElMessage.success('数量增加成功')
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message)
  }
}

// 减少物品数量
const decreaseQuantity = async () => {
  if (!item.value || item.value.quantity <= 1) return
  try {
    const newQuantity = item.value.quantity - 1
    // 在实际应用中，应当发送请求到服务器更新数量
    await inventoryStore.updateItemQuantity(itemId.value, newQuantity)
    // 重新获取最新数据以确保UI更新
    await fetchItemDetails()
    ElMessage.success('数量减少成功')
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message)
  }
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取物品状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '正常使用': return 'success'
    case '闲置': return 'info'
    case '已损坏': return 'danger'
    case '借出': return 'warning'
    case '需要替换': return 'warning'
    case '已过期': return 'danger'
    default: return 'info'
  }
}

// 返回到物品列表
const goBack = () => {
  router.back()
}

// 监听路由参数变化，重新加载数据
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      itemId.value = newId
      fetchItemDetails()
    }
  }
)

// 监听iconId变化，自动更新分类
watch(() => item.value?.iconId, (newIconId) => {
  if (newIconId) {
    // 获取选中图标的分类
    const iconCategory = itemsStore.getIconCategory(newIconId)
    if (iconCategory) {
      // 根据图标分类设置物品分类
      const categoryId = itemsStore.getCategoryIdByIconCategory(iconCategory)
      if (categoryId) {
        editForm.value.categoryId = categoryId
        // 如果在编辑模式，显示提示消息
        if (isEditing.value) {
          ElMessage.success(`已根据图标自动将物品分类设置为${itemsStore.getCategoryName(categoryId)}`)
        }
      }
    }
  }
}, { immediate: true })

onMounted(() => {
  fetchItemDetails()
})
</script>

<template>
  <div class="item-details-view">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载物品详情中...</p>
    </div>
    
    <template v-else-if="item">
      <!-- 头部区域 -->
      <div class="details-header">
        <div class="header-left">
          <el-button @click="goBack" type="text" size="small" class="back-button">
            <el-icon><i class="el-icon-arrow-left"></i></el-icon>
            返回
          </el-button>
          <h1 class="page-title">{{ isEditing ? '编辑物品' : '物品详情' }}</h1>
        </div>
        
        <div v-if="!isEditing" class="header-actions">
          <el-button type="primary" @click="enableEditing">编辑物品</el-button>
          <el-button type="danger" @click="deleteItem">删除物品</el-button>
        </div>
        
        <div v-else class="header-actions">
          <el-button type="primary" @click="saveChanges">保存</el-button>
          <el-button @click="cancelEditing">取消</el-button>
        </div>
      </div>
      
      <!-- 物品详情 -->
      <div class="details-content">
        <div class="details-card">
          <div class="item-icon">
            <IconSvg :icon="item.icon || 'default'" size="80" />
          </div>
          
          <div v-if="!isEditing" class="item-info">
            <h2 class="item-name">{{ item.name }}</h2>
            
            <div class="info-grid">
              <div class="info-item">
                <div class="info-label">类别</div>
                <div class="info-value">{{ categoryName || '-' }}</div>
              </div>
              
              <div class="info-item">
                <div class="info-label">位置</div>
                <div class="info-value">{{ item.specificLocation || item.location || '-' }}</div>
              </div>
              
              <div class="info-item">
                <div class="info-label">数量</div>
                <div class="info-value quantity-controls">
                  <span class="quantity">{{ item.quantity }}</span>
                  <div class="quantity-buttons">
                    <el-button type="primary" size="small" circle @click="increaseQuantity">+</el-button>
                    <el-button type="danger" size="small" circle @click="decreaseQuantity"
                      :disabled="item.quantity <= 1">-</el-button>
                  </div>
                </div>
              </div>
              
              <div class="info-item">
                <div class="info-label">状态</div>
                <div class="info-value">
                  <el-tag :type="getStatusTagType(item.status)">{{ item.status || '正常使用' }}</el-tag>
                </div>
              </div>
              
              <div class="info-item">
                <div class="info-label">购买日期</div>
                <div class="info-value">{{ formatDate(item.purchaseDate) }}</div>
              </div>
              
              <div class="info-item" v-if="item.expiryDate">
                <div class="info-label">过期日期</div>
                <div class="info-value">{{ formatDate(item.expiryDate) }}</div>
              </div>
            </div>
            
            <div class="info-notes" v-if="item.notes">
              <div class="info-label">备注</div>
              <div class="notes-content">{{ item.notes }}</div>
            </div>
          </div>
          
          <!-- 编辑表单 -->
          <div v-else class="item-edit-form">
            <el-form :model="editForm" label-position="top">
              <el-form-item label="物品名称">
                <el-input v-model="editForm.name" placeholder="输入物品名称"></el-input>
              </el-form-item>
              
              <el-form-item label="类别">
                <el-input :value="categoryName" readonly placeholder="分类将根据选择的图标自动设置"></el-input>
              </el-form-item>
              
              <el-form-item label="位置">
                <el-input v-model="editForm.specificLocation" placeholder="输入存放位置"></el-input>
              </el-form-item>
              
              <el-form-item label="数量">
                <el-input-number v-model="editForm.quantity" :min="1" style="width: 100%"></el-input-number>
              </el-form-item>
              
              <el-form-item label="状态">
                <el-select v-model="editForm.status" placeholder="选择状态" style="width: 100%">
                  <el-option label="正常使用" value="正常使用"></el-option>
                  <el-option label="闲置" value="闲置"></el-option>
                  <el-option label="已损坏" value="已损坏"></el-option>
                  <el-option label="借出" value="借出"></el-option>
                  <el-option label="需要替换" value="需要替换"></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="购买日期">
                <el-date-picker
                  v-model="editForm.purchaseDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              
              <el-form-item label="过期日期">
                <el-date-picker
                  v-model="editForm.expiryDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              
              <el-form-item label="备注">
                <el-input
                  v-model="editForm.notes"
                  type="textarea"
                  :rows="3"
                  placeholder="输入备注信息"
                ></el-input>
              </el-form-item>

              <el-form-item label="图标">
                <el-select v-model="editForm.icon" placeholder="选择图标" style="width: 100%">
                  <el-option label="默认" value="default"></el-option>
                  <el-option label="电子产品" value="electronics"></el-option>
                  <el-option label="家具" value="furniture"></el-option>
                  <el-option label="食品" value="food"></el-option>
                  <el-option label="衣物" value="clothing"></el-option>
                  <el-option label="日用品" value="daily"></el-option>
                  <el-option label="药品" value="medicine"></el-option>
                  <el-option label="空调" value="airConditioner"></el-option>
                  <el-option label="台灯" value="lamp"></el-option>
                  <el-option label="电风扇" value="fan"></el-option>
                  <el-option label="插座" value="socket"></el-option>
                  <el-option label="冰箱" value="refrigerator"></el-option>
                  <el-option label="显示器" value="monitor"></el-option>
                  <el-option label="吸尘器" value="vacuum"></el-option>
                  <el-option label="电吹风" value="hairDryer"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </template>
    
    <div v-else-if="!loading" class="error-state">
      <div class="error-icon">❓</div>
      <h3>找不到物品</h3>
      <p>无法加载物品详情，可能已被删除或不存在</p>
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<style scoped>
.item-details-view {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  padding: 0 6px;
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.back-button {
  margin-right: 16px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.details-content {
  flex: 1;
  padding: 24px 0;
  overflow-y: auto;
}

.details-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.item-icon {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 24px 0;
  text-align: center;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 0.9rem;
  color: #86868b;
  margin-bottom: 8px;
}

.info-value {
  font-size: 1rem;
  color: #1d1d1f;
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.quantity {
  font-size: 1rem;
  margin-right: 16px;
}

.quantity-buttons {
  display: flex;
  gap: 8px;
}

.info-notes {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.notes-content {
  font-size: 1rem;
  color: #1d1d1f;
  white-space: pre-line;
  margin-top: 8px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 3px solid rgba(0, 113, 227, 0.1);
  border-top-color: #0071e3;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #86868b;
  text-align: center;
}

.error-icon {
  font-size: 3rem;
  margin-bottom: 16px;
}

.error-state h3 {
  font-size: 1.2rem;
  font-weight: 500;
  margin: 0 0 8px;
  color: #1d1d1f;
}

.error-state p {
  margin-bottom: 24px;
}

.item-edit-form {
  padding: 0 16px;
}
</style> 